package com.ruoyi.ruo.file.service.impl;

import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.core.exception.file.InvalidExtensionException;
import com.ruoyi.common.core.utils.Assert;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.VideoUtil;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
import com.ruoyi.ruo.file.config.RuoYiConfig;
import com.ruoyi.ruo.file.service.FileUploadService;
import com.ruoyi.ruo.file.utils.FileUploadUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import static com.ruoyi.common.core.utils.file.MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION;
import static com.ruoyi.common.core.utils.file.MimeTypeUtils.IMAGE_EXTENSION;

/**
 * @author songpin566
 * @date 2023/09/08
 **/
@Service
public class FileUploadServiceImpl implements FileUploadService {


    @Override
    public String upload(MultipartFile file) throws IOException, InvalidExtensionException {
        String extension = FileUploadUtils.getExtension(file);
        Assert.isTrue(StringUtils.isEmpty(extension)||
                !Arrays.asList(DEFAULT_ALLOWED_EXTENSION).contains(extension),"文件格式不正确!");

        //判断是否是图片
        if(Arrays.asList(IMAGE_EXTENSION).contains(extension)){
            //压缩图片再上传
            String imagePath =FileUploadUtils.compressImage(file,IMAGE_EXTENSION);
            return imagePath;
        }
        //如果是其他类型格式的文件先上传
        String url = FileUploadUtils.upload(file);
        // 通过后缀名判断文件类型是否为视频类型
        if (Arrays.asList(MimeTypeUtils.VIDEO_EXTENSION).contains(extension)) {
            // 视频文件进行压缩替换 文件夹
            String name = FileUtil.getName(url);//20.Redis的Java客户端-RedisTemplate的RedisSerializer_20230908163323A001.mp4
            String originFilePath = RuoYiConfig.getProfile() + url.substring(8);
            String originFolderPath = originFilePath.replace(name, "");
            String tempFilePath = originFolderPath + RandomStringUtils.randomNumeric(20) + "." + extension;
            FileUtil.copy(originFilePath, tempFilePath, false);
            VideoUtil.compressionVideo(new File(tempFilePath), name, true);
        }

        return url;
    }


}
